"""新闻CRUD模型"""
from sqlalchemy.orm import Session
from soulapi.models import model_newstype
from soulapi.schemas import schema_newstype


def get_newstypes(db: Session, skip: int = 0, limit: int = 100):
    query_newstype = db.query(model_newstype.NewsType).offset(skip).limit(limit).all()
    # return_data = query_newstype.to_dict(keys=("nety_id", "nety_name", "nety_intro"))
    # print(type(query_newstype))
    return query_newstype


def get_newstype(db: Session, id: int):
    query_newstype = db.query(model_newstype.NewsType).filter(model_newstype.NewsType.nety_id == id).first()
    # return_data = query_newstype.to_dict(keys=("nety_id", "nety_name", "nety_intro"))
    return query_newstype


def get_newstype_by_name(db: Session, name: str):
    query_newstype = db.query(model_newstype.NewsType).filter(model_newstype.NewsType.nety_name == name).first()
    # return_data = query_newstype.to_dict(keys=("nety_id", "nety_name", "nety_intro"))
    return query_newstype


def create_newstype(db: Session, newstype: schema_newstype.NewsTypeCreate):
    new_newstype = model_newstype.NewsType(**newstype.dict())
    db.add(new_newstype)
    db.commit()
    # db.refresh(new_newstype)
    return_data = new_newstype.to_dict(keys=("nety_id", "nety_name"))
    return return_data


def update_newstype(db: Session, newstype: schema_newstype.NewsTypeCreate):
    db.query(model_newstype.NewsType).filter(model_newstype.NewsType.nety_name == newstype.nety_name).update(newstype)
    db.commit()
    return db.query(model_newstype.NewsType).filter(model_newstype.NewsType.nety_name == newstype.nety_name).first()


def delete_newstype(db: Session, id: int):
    db.query(model_newstype.NewsType).filter(model_newstype.NewsType.nety_id == id).delete()
    db.commit()
    return {'Result': '{nety_id}号文章分类删除成功'}


def delete_newstype_by_name(db: Session, name: str):
    db.query(model_newstype.NewsType).filter(model_newstype.NewsType.nety_name == name).delete()
    db.commit()
    return {'Result': '{nety_name}————>文章分类删除成功'}
